package com.zondy.mapgis.android.activity;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.zondy.dizhi.server.util.APPNetWork;
import com.zondy.dizhi.server.util.GsonUtil;
import com.zondy.mapgis.android.base.BaseActivity;
import com.zondy.mapgis.android.internal.utils.ToastUtil;
import com.zondy.mapgis.android.model.EntityUser;
import com.zondy.mapgis.android.utils.DialogUtil;
import com.zondy.mapgis.android.utils.FileOperation;
import com.zondy.mapgis.android.utils.SharedUtils;
import com.zondy.mapgis.explorer.R;

public class LoginActivity extends BaseActivity implements OnClickListener
{
	private TextView mTitle = null;
	public EditText mUserNameEt = null;
	public EditText mPasswordEt = null;
	public EditText mLoginErrorEt = null;

	private static final int LOGIN_ERROR = 1;
//	private static final int TIMEOUT_ERROR = 2;
	private static final int NET_ERROR = -1;
	private EntityUser mUser = new EntityUser();

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		// 透明状态栏
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
		// 透明导航栏
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

		initView();
	}

	private void initView()
	{
		mTitle = (TextView) findViewById(R.id.title_text);
		mTitle.setText("登录");
		mUserNameEt = (EditText) findViewById(R.id.et_username);
		mPasswordEt = (EditText) findViewById(R.id.et_password);
		mLoginErrorEt = (EditText) findViewById(R.id.login_error_ets);

		findViewById(R.id.title_back).setOnClickListener(this);
		findViewById(R.id.login_btn).setOnClickListener(this);
		findViewById(R.id.register_text).setOnClickListener(this);
		
		APPNetWork.checkNetState(this);
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.login_btn:
			final String userName = mUserNameEt.getText().toString();
			final String passWord = mPasswordEt.getText().toString();
			DialogUtil.createProgressDialog(this, "正在登录...", "登录");
			new Thread(new Runnable()
			{
				@Override
				public void run()
				{
					login(userName, passWord);
				}
			}).start();

			break;
		case R.id.register_text:
			startActivity(new Intent(getApplicationContext(), RegisterActivity.class));
			break;
		case R.id.title_back:
//			startActivity(new Intent(getApplicationContext(), MapActivity.class));
			finish();
			break;

		default:
			break;
		}

	}

	public Handler mHandler = new Handler()
	{
		public void handleMessage(android.os.Message msg)
		{
			if (msg.what == LOGIN_ERROR)
			{
				mLoginErrorEt.setVisibility(View.VISIBLE);
				mLoginErrorEt.setText("账号和密码不匹配");
			}
			else if (msg.what == NET_ERROR)
			{
				mLoginErrorEt.setVisibility(View.VISIBLE);
				mLoginErrorEt.setText("连接服务器异常");
			}

		};
	};

	/**
	 * 登录
	 * 
	 * @param strUserName
	 * @param strPassword
	 */
	private void login(String strUserName, String strPassword)
	{
		if (strUserName.length() == 0)
		{
			ToastUtil.showToast(getApplicationContext(), "请输入用户名/邮箱/手机号");
			return;
		}

		if (strPassword.length() == 0)
		{
			ToastUtil.showToast(this, "请输入密码");
			return;
		}

		HttpURLConnection connection = null;
		byte[] data = null;
		String strResult = null;
		Message msg = new Message();

		URL postUrl;
		try
		{
			postUrl = new URL("http://www.smaryun.com/ucenter/user.php?a=login");
			connection = (HttpURLConnection) postUrl.openConnection();
			// 设置连接超时时间
			connection.setConnectTimeout(10 * 1000);
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			connection.connect();
			DataOutputStream out = new DataOutputStream(connection.getOutputStream());
			String content = String.format("username=%s&password=%s&remember=false&format=json", strUserName, strPassword);
			out.writeBytes(content);
			out.flush();
			out.close();
			// 判断请求是否成功
			if (connection.getResponseCode() != 200)
			{
				Log.e("网络异常:", "网络异常");
				return;
			}
			else
			{
				// 获取返回的数据
				data = FileOperation.InputStreamToByte(connection.getInputStream());
				// 关闭连接
				connection.disconnect();

				strResult = GsonUtil.getBytesToString(data);
				Log.e("strResult:", strResult);
			}
			JSONObject jsonObject = new JSONObject(strResult);
			String error = jsonObject.getString("error");
			if (error.equalsIgnoreCase("0"))
			{
				Log.e("登录成功:", strResult);
//				startActivity(new Intent(getApplicationContext(), MapActivity.class));
				mUser.setUserName(strUserName);
				mUser.setPassword(strPassword);
				SharedUtils.getInstance().saveUserInfo(getApplicationContext(), mUser);
				finish();
			}
			else
			{
				msg.what = LOGIN_ERROR;
				Log.e("账号和密码不匹配，你还有四次机会", strResult);
			}
			
		}
		catch (MalformedURLException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			msg.what = NET_ERROR;
			e.printStackTrace();
		}
		catch (JSONException e)
		{
			e.printStackTrace();
		}

		mHandler.sendMessage(msg);
		DialogUtil.cancelProgressDialog();
	}

}
